/**
 * Created by wdp on 2019/11/18.
 */

import axios from 'axios'
import router from '@/router'
import {getCookie,delCookie} from './index';
//md5 base64加密处理
const Base64 = require("js-base64").Base64,
      $md5 = require('js-md5');

let service = (url, params) => {
  //登录后randomKey
  let entity_random = getCookie('token') ? getCookie('token') : '';
  //base64编码
  let params_base =  Base64.encode(JSON.stringify(params));
  //md5加密
  let sign = $md5(params_base + entity_random);
  // 创建axios实例
  return axios({
    baseURL: process.env.BASE_API, // api 的 base_url
    url: url,
    method: 'post',
    data: url == 'login'? params:{
      "object": params_base ,"sign":sign
    },
    timeout: 10000 // 请求超时时间
  });
};


// request拦截器
axios.interceptors.request.use(
  config => {
    let entity_headers = {
      'Authorization': getCookie('token') ? 'Bearer-'+ getCookie('token') : 'Bearer-', // 让每个请求携带自定义token
      'Content-Type':'application/json;charset=UTF-8'
    };
    config.headers = entity_headers;
    return config
  },
  error => {
    // Do something with request error
    Promise.reject(error)
  }
);
// response 拦截器
axios.interceptors.response.use(
  response => {
    /**
     * code为非200是抛错 可结合自己业务进行修改
     */
    const res = response.data;
    if (res.code !== 200) {
      // 401:未登录或已过期; 407:权限不足，无法访问该资源;  416:接口，因为认证失败，无法访问系统资源;418:账户被禁用，请联系管理员
      if (res.code === 401 || res.code === 407 || res.code === 416 || res.code === 418) {
        alert(res.message);
        delCookie('token');
        router.push("/");
      }
    }
    return response.data;
  },
  error => {
    console.log('err' + error); // for debug
    alert(error.message);
    return Promise.reject(error)
  }
);
export default service
